import com.fasterxml.jackson.databind.ObjectMapper;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


class User{
    public String username;
    public String password;
}

@WebServlet("/json")
public class JsonServlet extends HttpServlet {
        /**
         * 此处约定客户端body按照json格式来进行传输
         * {
         *     username:"zhangshan"
         *     password:"123"
         * }
         */
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ObjectMapper objectMapper = new ObjectMapper();
            User user = objectMapper.readValue(req.getInputStream(),User.class);//从字符串到对象
            System.out.println("username= " + user.username +", password= "+user.password);
            //也可以java对象转成json字符串
            String userString = objectMapper.writeValueAsString(user);
            System.out.println("userString: "+userString);
            resp.getWriter().write("ok");
    }

}
